import { constantRoutes } from '@/router'
import { getRouters } from '@/api/menu'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'
import path from 'path'
import Iframe from '@/components/InnerIframe'

const permission = {
  state: {
    routes: [],
    addRoutes: [],
    sidebarRouters: [],
    fullPathRoutes: [], // 子路由的path为全路径,用于进入时判断首页然后跳转
    homePath: '',
    searchPool: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    },
    SET_SIDEBAR_ROUTERS: (state, routers) => {
      state.sidebarRouters = constantRoutes.concat(routers)
    },
    SET_FULLPATH_ROUTERS: (state, routers) => {
      state.fullPathRoutes = routers
    },
    SET_HOME: (state, path) => {
      state.homePath = path
    },
    SET_SearchPool: (state, routers) => {
      state.searchPool = routers
    }
  },
  actions: {
    SetHomePath({ commit }, path) {
      commit('SET_HOME', path)
    },
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        getRouters().then(res => {
          const fdata = JSON.parse(JSON.stringify(res.data))
          const fullPathRoutes = fullAsyncRouter(fdata, true)
          commit('SET_FULLPATH_ROUTERS', fullPathRoutes)
          const sdata = JSON.parse(JSON.stringify(res.data))
          const rdata = JSON.parse(JSON.stringify(res.data))
          const sidebarRoutes = filterAsyncRouter(sdata)
          sidebarRoutes.push({ path: '*', redirect: '/404', hidden: true })
          const rewriteRoutes = filterAsyncRouter(rdata, true)
          rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
          commit('SET_ROUTES', rewriteRoutes)
          commit('SET_SIDEBAR_ROUTERS', sidebarRoutes)
          const search = JSON.parse(JSON.stringify(res.data))
          const searchPool = pool(search)
          commit('SET_SearchPool', searchPool)
          console.log(searchPool)
          resolve(sidebarRoutes)
        })
      })
    }
  }
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, isRewrite = false) {
  return asyncRouterMap.filter(route => {
    if (isRewrite && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, isRewrite)
    }
    if (route.component) {
      // Layout ParentView Iframe 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else if (route.component === 'Iframe') {
        route.component = Iframe
      } else {
        route.component = loadView(route.component)
      }
    }
    // 批量处理affix
    if (route.meta && route.meta.affix && route.meta.affix === '0') {
      route.meta.affix = true
    } else {
      delete route.meta.affix
    }
    // 批量处理target
    if (route.meta && route.meta.isFrame && route.meta.isFrame === '1') {
      delete route.meta.isFrame
      delete route.meta.target
    }
    return true
  })
}

function filterChildren(childrenMap) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView') {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    children = children.concat(el)
  })
  // console.log(children)
  return children
}

/* 构造全路径fullPathRouter用于筛选首页 */
function fullAsyncRouter(asyncRouterMap, isRewrite = false) {
  return asyncRouterMap.filter(route => {
    if (isRewrite && route.children) {
      route.children = fullPathChildren(route.children, route.path)
    }
    // 批量处理affix
    if (route.meta && route.meta.affix && route.meta.affix === '0') {
      route.meta.affix = true
    } else {
      delete route.meta.affix
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = fullAsyncRouter(route.children, route, isRewrite)
    }
    // 批量处理target
    if (route.meta && route.meta.isFrame && route.meta.isFrame === '1') {
      delete route.meta.isFrame
      delete route.meta.target
    }
    return true
  })
}

function fullPathChildren(childrenMap, beforePath) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      el.children.forEach(c => {
        c.path = beforePath + '/' + el.path + '/' + c.path
        if (c.children && c.children.length) {
          children = children.concat(fullPathChildren(c.children, c.path))
          return
        }
        children.push(c)
      })
      return
    } else {
      el.path = path.resolve(beforePath, el.path)
    }
    children = children.concat(el)
  })
  return children
}

function pool(asyncRouter) {
  asyncRouter.map(route => {
    if (route.children) {
      route.children = poolChildren(route.children, route.path)
    }
    // if (route.children != null && route.children && route.children.length) {
    //   route.children = pool(route.children)
    // }
  })
  return asyncRouter
}
function poolChildren(childrenMap, beforePath) {
  childrenMap.forEach(el => {
    if (el.children && el.children.length) {
      el.children.forEach(c => {
        c.path = beforePath + '/' + el.path + '/' + c.path
        if (c.children && c.children.length) {
          fullPathChildren(c.children, c.path)
        }
      })
    } else {
      el.path = path.resolve(beforePath, el.path)
    }
  })
  return childrenMap
}

export const loadView = view => {
  // 路由懒加载
  return resolve => require([`@/views/${view}`], resolve)
}

export default permission
